package cn.snmp.mutual.org.opennms.protocols.icmp;

import cn.snmp.mutual.org.opennms.protocols.exceptions.InsufficientDataException;
import cn.snmp.mutual.org.opennms.protocols.ip.OC16ChecksumProducer;

public final class AddressMaskReply extends ICMPHeader {
    private int m_mask;

    public AddressMaskReply() {
        super((byte) 18, (byte) 0);
        this.m_mask = 0;
    }

    public AddressMaskReply(final byte[] buf, final int offset) {
        this.loadFromBuffer(buf, offset);
    }

    @Override
    public void computeChecksum() {
        final OC16ChecksumProducer summer = new OC16ChecksumProducer();
        super.computeChecksum(summer);
        summer.add(this.m_mask);
        this.setChecksum(summer.getChecksum());
    }

    public int storeToBuffer(final byte[] buf, int offset) {
        if (buf.length < offset + 12) {
            throw new ArrayIndexOutOfBoundsException("Array index overflow in buffer build");
        }
        this.computeChecksum();
        offset = this.storeToBuffer(buf, offset);
        buf[offset++] = (byte) (this.m_mask >> 24 & 0xFF);
        buf[offset++] = (byte) (this.m_mask >> 16 & 0xFF);
        buf[offset++] = (byte) (this.m_mask >> 8 & 0xFF);
        buf[offset++] = (byte) (this.m_mask & 0xFF);
        return offset;
    }

    public int loadFromBuffer(final byte[] buf, int offset) {
        if (buf.length < offset + 12) {
            throw new InsufficientDataException("Insufficient data to load ICMP header");
        }
        offset = super.loadFromBuffer(buf, offset);
        if (this.getType() != 18) {
            throw new IllegalArgumentException("The buffer did not contain an Address Mask Reply");
        }
        this.m_mask = (byteToInt(buf[offset++]) << 24 | byteToInt(buf[offset++]) << 16 | byteToInt(buf[offset++]) << 8 | byteToInt(buf[offset++]));
        return offset;
    }

    public int getAddressMask() {
        return this.m_mask;
    }

    public void setAddressMask(final int mask) {
        this.m_mask = mask;
    }

    @Override
    public byte[] toBytes() {
        final byte[] buf = new byte[12];
        this.storeToBuffer(buf, 0);
        return buf;
    }
}
